package br.com.fogas.medicao.business;

import java.sql.SQLException;

import android.support.v4.app.FragmentActivity;
import br.com.fogas.database.FogasDatabase;
import br.com.fogas.database.entidade.NotaFiscal;
import br.com.fogas.database.entidade.PlanoVisitas;
import br.com.fogas.database.enums.PlanoVisitaStatusEnum;
import br.com.fogas.medicao.R;
import br.com.fogas.medicao.activity.ImpressaoNotaFragment;
import br.com.fogas.utils.dialog.DialogAlert;
import br.com.fogas.utils.task.ServiceTask;
import br.com.fogas.utils.task.ServiceTaskBusiness;
import br.com.fogas.medicao.application.Constants;
import br.com.fogas.medicao.application.LoadFragment;
import br.com.fogas.notafiscal.NotaFiscalEngine;

public class EmitirNotaContigenciaBusiness implements ServiceTaskBusiness {

	private FogasDatabase database;
	private NotaFiscal notaFiscal;
	private FragmentActivity activity;

	public EmitirNotaContigenciaBusiness(FragmentActivity activity, FogasDatabase database, NotaFiscal notaFiscal) {
		this.activity = activity;
		this.database = database;
		this.notaFiscal = notaFiscal;
	}
	
	@Override
	public void start(ServiceTask serviceTask) {
		try {
			//Grava nota contigencia
			NotaFiscal notaContigencia = NotaFiscalEngine.salvarNotaContigencia(database, notaFiscal);
			
			//Finaliza o Plano de Visita
			PlanoVisitas planoVisitas = notaContigencia.getTx_plano_visitas();
			planoVisitas.setStatus(PlanoVisitaStatusEnum.FINALIZADO.getId());
			database.getPlanoVisitas().update(planoVisitas);
			
			//Atualiza a ultima nota emitida
			database.getNotaControle().atualizarUltimaNotaEmitida();
			
			redirecionarTelaImpressao(notaContigencia);
		} catch (SQLException e) {
			DialogAlert.newInstance()
			.setTitle(R.string.dialog_title_alert)
			.setMessage(R.string.simulacao_nota_erro_emissao_contigencia)
			.showDialog(activity.getSupportFragmentManager());
		}
	}
	
	private void redirecionarTelaImpressao(NotaFiscal notaContigencia) {
		ImpressaoNotaFragment impressaoFragment = ImpressaoNotaFragment.newInstance(notaContigencia);
		LoadFragment load = new LoadFragment(activity.getSupportFragmentManager());
		load.initializeFragment(true, impressaoFragment, Constants.FRAGMENT_IMPRESSAO_NOTA);
	}
}